package com.groupjx.tools;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.MD5;
import cn.hutool.json.JSONUtil;

import java.util.Map;
import java.util.TreeMap;

public class JXUtils {


    /**
     * 签名
     *
     * @param paramsMap
     * @param secretKey
     */
    public static void sign(Map<String, Object> paramsMap, String secretKey) {
        //请求参数拼接签名
        paramsMap.put("timestamp", System.currentTimeMillis());
        paramsMap.put("nonce", IdUtil.simpleUUID());
        String paramStr = joinParams(new TreeMap(paramsMap));
        String sign = hash(paramStr, secretKey);
        paramsMap.put("sign", sign);
    }


    /**
     * 拼接参数
     *
     * @param paramsMap
     * @return
     */
    public static String joinParams(Map<String, Object> paramsMap) {
        StringBuilder sb = new StringBuilder();
        for (String key : paramsMap.keySet()) {
            Object value = paramsMap.get(key);
            if (!ObjectUtil.isEmpty(value)) {
                if (value instanceof String || value instanceof Long || value instanceof Integer || value instanceof Double || value instanceof Float) {
                    sb.append(key).append("=").append(value).append("&");
                } else {
                    value = JSONUtil.toJsonStr(value);
                    sb.append(key).append("=").append(value).append("&");
                }
            }
        }
        if (sb.length() > 0) {
            sb.deleteCharAt(sb.length() - 1);
        }
        return sb.toString();
    }


    /**
     * 加密
     *
     * @param paramStr
     * @param secretKey
     * @return
     */
    public static String hash(String paramStr, String secretKey) {
        //拼接密钥
        String formatParams = StrUtil.format(paramStr + "&key={}", secretKey);
        //签名加密
        return MD5.create().digestHex(formatParams);
    }


}
